<template>
  <div class="select-container">
    <van-cell :title="title" value-class="cell" :value="label || placeholder" @click="isShowPopup = true" is-link>
      <template slot="right-icon">
        <van-icon name="clear" class="clear" v-if="value || value === 0" @click.stop="clear" />
      </template>
    </van-cell>
    <van-popup v-model="isShowPopup" position="bottom" class="popup">
      <van-picker
        title="选择选项"
        show-toolbar
        :columns="option"
        value-key="text"
        :default-index="defaultIndex"
        @confirm="onConfirm"
        @cancel="isShowPopup = false"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'Query',
  components: {},
  props: {
    title: {
      type: String,
      default: '筛选查询'
    },
    value: {
      default: () => ''
    },
    option: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data () {
    return {
      isShowPopup: false
    }
  },
  computed: {
    defaultIndex () {
      const list = this.option || []
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.value === this.value) {
          return i
        }
      }
      return 0
    },
    label () {
      const list = this.option || []
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.value === this.value) {
          return item.text
        }
      }
      return this.value
    }
  },
  methods: {
    onConfirm (e, val) {
      this.isShowPopup = false
      this.$emit('input', e.value)
      this.$emit('selected', e)
    },
    clear () {
      this.$emit('input', undefined)
    }
  }
}
</script>

<style scoped lang='less'>
.select-container {
  .cell {
    text-align: left;
    flex: 2.2;
  }
  .clear {
    margin-top: 4px;
    font-size: 16px; color: #ccc;
  }
}
</style>
